package com.it.nongchanping.controller;

import com.it.nongchanping.entity.Product;
import com.it.nongchanping.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * 产品控制器
 */
@Controller
@RequestMapping("/product")
public class ProductController {
    
    @Autowired
    private ProductService productService;
    
    /**
     * 产品列表页
     */
    @GetMapping("/list")
    public String productList(@RequestParam(value = "category", required = false) String category, Model model) {
        List<Product> products;
        if (category != null && !category.isEmpty()) {
            products = productService.getProductsByCategory(category);
            model.addAttribute("currentCategory", category);
        } else {
            products = productService.getAvailableProducts();
        }
        model.addAttribute("products", products);
        
        // 产品分类
        model.addAttribute("categories", List.of("山区水果", "手工艺品", "有机粮油", "特色蔬菜", "畜牧产品"));
        
        return "product/list";
    }
    
    /**
     * 产品详情页
     */
    @GetMapping("/detail/{id}")
    public String productDetail(@PathVariable Long id, Model model) {
        Product product = productService.getProductById(id);
        if (product == null) {
            return "redirect:/product/list";
        }
        model.addAttribute("product", product);
        
        // 推荐相关产品
        List<Product> relatedProducts = productService.getProductsByCategory(product.getCategory());
        relatedProducts.removeIf(p -> p.getId().equals(id)); // 移除当前产品
        model.addAttribute("relatedProducts", relatedProducts);
        
        return "product/detail";
    }
    
    /**
     * 产品搜索
     */
    @GetMapping("/search")
    public String searchProducts(@RequestParam String keyword, Model model) {
        List<Product> products = productService.searchProducts(keyword);
        model.addAttribute("products", products);
        model.addAttribute("keyword", keyword);
        return "product/search";
    }
} 